<?php

namespace backend\controllers;

use backend\models\AppModules;
use backend\models\search\AppModulesSearch;
use yii\helpers\FileHelper;
use yii\web\NotFoundHttpException;
use nickdenry\grid\toggle\actions\ToggleAction;

/**
 * Class AppModulesController
 * @property-read  string $packageUrl
 * @package backend\controllers
 */
class AppModulesController extends BaseController
{

    public function actions()
    {
        return [
            'toggle' => [
                'class' => ToggleAction::class,
                'modelClass' => AppModules::class,
            ],
        ];
    }

    /**
     * Lists all AppModules models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new AppModulesSearch();
        $dataProvider = $searchModel->search(request()->queryParams);

        return $this->render('index', [
            'searchModel'  => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Creates a new AppModules model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new AppModules();
        $model->loadDefaultValues();
        $model->id = uniqid();
        if ($model->load(post()) && $model->save()) {
            return $this->redirect(['index']);
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing AppModules model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(post()) && $model->save()) {
            return $this->redirect(['index']);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * actionDelete      * @param $id
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * actionImport
     * @return \yii\web\Response
     * @throws \yii\base\ErrorException
     */
    public function actionImport()
    {
        if(request()->isPost){
            try {
                $zipFile = post('zipFile');
                if(!is_file($zipFile)){
                    throw new \Exception('下载扩展文件失败.');
                }
                $zipArchive = new \ZipArchive();
                $extractPath = dirname($zipFile).'/'.uniqid();
                if($zipArchive->open($zipFile) !== true || $zipArchive->extractTo($extractPath) !== true || $zipArchive->close() !== true ){
                    throw new \Exception('解压扩展文件失败.');
                }
                @unlink($zipFile);
                $dst = dirname(app()->basePath).'/modules';
                //复制文件
                FileHelper::copyDirectory($extractPath,$dst);
                //查找模块信息
                $files = FileHelper::findFiles($extractPath,['only'=>['modulesInfo.json']]);

                if(empty($files[0])){
                    throw new \Exception('获取扩展信息失败.');
                }

                $modulesInfo = json_decode(file_get_contents($files[0]),1);
                if(empty($model = AppModules::findOne(['class'=>$modulesInfo['class']]))){
                    $model = new AppModules();
                    $model->loadDefaultValues();
                }
                $model->load($modulesInfo,'');
                if(!$model->save()){
                    throw new \Exception('添加扩展信息到数据库失败.');
                }
                cache()->flush();
                return $this->asSuccessJson();
            }catch (\Throwable $e){
                exceptionFormat($e);
                return $this->asErrorJson('操作失败:'.$e->getMessage());
            } finally {
                FileHelper::removeDirectory($extractPath??null);
            }
        }
    }

    /**
     * Finds the AppModules model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return AppModules the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = AppModules::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
